package code;

import java.util.Stack;

public class Code227 {
	
    public int calculate(String s) {
    	Stack<Integer> numSck=new Stack<Integer>();
    	Stack<Character> opSck=new Stack<Character>();
    	int i=0;
    	s=s.replace(" ", "");
    	int len=s.length();
    	int result=0;
    	while(i<len){
    		char c=s.charAt(i);
    		//nums
    		if(c>='0' && c<='9'){
    			int x=0;
    			while(i<len && s.charAt(i)>='0' && s.charAt(i)<='9'){
    				x*=10;
    				x+=s.charAt(i)-'0';
    				i++;
    			}
    			numSck.push(x);
    		}
    		//运算符
    		else{
    			if(c=='*' || c=='/'){
					while(!opSck.isEmpty() && (opSck.peek()=='*' || opSck.peek()=='/')){
						int a=numSck.pop();
						int b=numSck.pop();
						char op=opSck.pop();
						if(op=='*')
							b*=a;
						else
							b/=a;
						numSck.push(b);
					}
    			}
    			else{
    				while(!opSck.isEmpty()){
    					int a=numSck.pop();
    					int b=numSck.pop();
    					char op=opSck.pop();
    					if(op=='*')
    						b*=a;
    					else if(op=='/')
    						b/=a;
    					else if(op=='+')
    						b+=a;
    					else 
    						b-=a;
    					numSck.push(b);
    				}
    			}
    			opSck.push(c);
    			i++;
    		}
    		//如果处理完所有的字符,则对栈内运算
    		if(i==len){
				while(!opSck.isEmpty()){
					int a=numSck.pop();
					int b=numSck.pop();
					char op=opSck.pop();
					if(op=='*')
						b*=a;
					else if(op=='/')
						b/=a;
					else if(op=='+')
						b+=a;
					else 
						b-=a;
					numSck.push(b);
				}
				if(!numSck.isEmpty())
					result=numSck.pop();
				else 
					result=0;
    		}
    	}
        return result;
    }
    public static void main(String[] args){
    	System.out.println(new Code227().calculate("1-1+1"));
    }
}
